package middleware

import (
	"fitness/go-admin/pkg/cache"
	"fitness/go-admin/pkg/errcode"
	"fitness/go-admin/pkg/response"
	"fitness/go-admin/pkg/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			response.Error(c, errcode.Unauthorized, "")
			c.Abort()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			response.Error(c, errcode.Unauthorized, "授权格式错误")
			c.Abort()
			return
		}

		token := parts[1]

		// 检查Token是否在黑名单中
		if cache.RedisClient != nil && cache.IsInBlacklist(token) {
			response.Error(c, errcode.TokenBlacklisted, "")
			c.Abort()
			return
		}

		claims, err := utils.ParseToken(token)
		if err != nil {
			response.Error(c, errcode.InvalidToken, "")
			c.Abort()
			return
		}

		c.Set("userId", claims.UserID)
		c.Next()
	}
}
